/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: Frank
 * 系统版本: 1.0.0
 * 开发人员: Frank
 * 开发时间: 2019/12/12 11:17
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.spring.arch.uaa.service;

import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.uaa.errorcode.UaaErrorCode;
import com.spring.arch.uaa.model.Organization;
import com.spring.arch.uaa.model.OrganizationEmployee;
import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.uaa.model.Organization;
import com.spring.arch.uaa.model.OrganizationEmployee;
import com.spring.arch.uaa.repository.OrganizationEmployeeRepository;
import com.spring.arch.uaa.repository.OrganizationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import static com.spring.arch.uaa.errorcode.UaaErrorCode.E2001003001;
import static com.spring.arch.uaa.errorcode.UaaErrorCode.E2001003003;

/**
 * 组织服务层接口
 *
 * @author Frank
 * @version 1.0.0.1
 * @since 2019/12/12 11:17
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrganizationService {

    @Autowired
    private OrganizationRepository organizationRepository;

    @Autowired
    private OrganizationEmployeeRepository organizationEmployeeRepository;

    public Organization save(Organization model) {

        Optional<Organization> optional = organizationRepository.findByParentAndNameAndDisableFalse(model.getParent(),
                model.getName());

        boolean flag = model.getId() == null && optional.isPresent()
                || model.getId() != null && optional.isPresent() && !optional.get().getId().equals(model.getId());

        if(flag) {

            throw ExceptionHolder.serviceException(UaaErrorCode.E2001003003, Organization.class.getSimpleName());
        }

        return organizationRepository.save(model);
    }

    public void delete(UUID id) {

        // 要删除的组织
        Organization organization = organizationRepository.findById(id).orElseThrow(() ->
                ExceptionHolder.serviceException(UaaErrorCode.E2001003001, Organization.class.getSimpleName()));

        // 要删除的所有组织
        List<Organization> orientationList = getChildrenOrganization(organization);
        orientationList.add(organization);

        // 要删除的组织的父组织
        Organization parentOrganization = organization.getParent();

        // 要删除的所有员工
        List<OrganizationEmployee> organizationEmployeeSet =
                organizationEmployeeRepository.findByOrganizationIn(orientationList);

        // 改变组织
        organizationEmployeeSet.forEach(l -> {

            if(organizationEmployeeRepository.findByOrganizationAndEmployee(parentOrganization, l.getEmployee()).isPresent()) {

                organizationEmployeeRepository.deleteById(l.getId());
            } else {

                l.setOrganization(parentOrganization);
                organizationEmployeeRepository.save(l);
            }
        });

        orientationList.forEach(l -> {
            l.setName(l.getName() + "(已删除)");
            l.setDisable(true);
        });
    }

    public List<Organization> getChildrenOrganization(Organization organization) {

        List<Organization> list = new ArrayList<>();

        List<Organization> orientationList =
                organizationRepository.findAllByParentIdAndDisableFalseOrderByCreatedDate(organization.getId());

        orientationList.forEach(l -> list.addAll(getChildrenOrganization(l)));
        list.addAll(orientationList);

        return list;
    }
}
